<template>
  <div class="messagelist">
    <!-- 头部搜索 -->
    <Input />
    <!-- 中间列表 -->
    <MessageList :userlist="userlist"  />
  </div>
</template>

<script>
import Input from "@/components/message/Input";
import MessageList from "@/components/message/MessageList";
import { getUserlist } from "@/api/data";
export default {
  data() {
    return {
      userlist: [],
     
    };
  },

  components: {
    Input,
    MessageList,
  },
  mounted() {
    // 监听是否有人发消息
    this.$socket.on("getmsg",(data)=>{
      // console.log(data)
      // 当前消息存到vuex,和当前对象聊天
      this.$store.commit("setnewmessage",data.msg)

      // 将每一个消息都要存到local
      let arr=JSON.parse(localStorage.getItem(`msglist-${this.$store.state.userdata._id}-${data.msg.from_id}`)) || []
      arr.push(data.msg)
       localStorage.setItem(
          `msglist-${this.$store.state.userdata._id}-${data.msg.from_id}`,
          JSON.stringify(arr)
        );
      
    })
    
    // 获取整个用户列表
    this.$socket.emit("userlist", {
      _id: this.$store.state.userdata._id,
    });
    this.$socket.on("userlist", (data) => {
      if (data.code == 200) {
        let userdata = JSON.parse(sessionStorage.getItem("userdata"));
        this.userlist = data.data.filter((item) => {
          item.noreadnumber = 0;
          return item._id != userdata._id;
        });
      }
    });

    // 获取当前用户的所有的未阅读消息
    this.$socket.emit("allnoread", {
      _id: this.$store.state.userdata._id,
    });

    this.$socket.on("allnoread", (data) => {
      let data1 = data.data;

      for (let i = 0; i < data1.length; i++) {
        for (let j = 0; j < this.userlist.length; j++) {
          if (this.userlist[j]._id == data1[i].from_id) {
            this.userlist[j].noreadnumber++;
          }
        }
      }
    });
  },
};
</script>

<style>
ul {
  height: 1500px;
  background-color: blue;
}
</style>